<?php


/**
 * 判断当前用户终端是否为微信
 */
function is_weixin() {
    if (!(strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") === false)) {
        return true;
    }
    return false;
}

function curlRequest($url, $isPost, $data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if ($isPost) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    } else {
        $url =  $url . '?' . http_build_query($data);
    }
    curl_setopt($ch, CURLOPT_URL, $url);

    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

function getAccessToken() {
    global $config;

    $mem = new Memcached();
    $mem->addserver("memcached",11211);

    if(!$mem->get("AccessToken2")) {
        $url = sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",$config['AppId'],$config['AppSecret']);
        $content = file_get_contents($url);
        $data = json_decode($content,true);

        if(!empty($data['access_token'])) {
            $mem->set("AccessToken2",$data['access_token'],time()+10);
        }
    }
    return $mem->get("AccessToken2");
}


function getSignature($str, $key) {
    $signature = "";
    if (function_exists('hash_hmac')) {
        $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
    } else {
        $blocksize = 64;
        $hashfunc = 'sha1';
        if (strlen($key) > $blocksize) {
            $key = pack('H*', $hashfunc($key));
        }
        $key = str_pad($key, $blocksize, chr(0x00));
        $ipad = str_repeat(chr(0x36), $blocksize);
        $opad = str_repeat(chr(0x5c), $blocksize);
        $hmac = pack(
            'H*', $hashfunc(
                ($key ^ $opad) . pack(
                    'H*', $hashfunc(
                        ($key ^ $ipad) . $str
                    )
                )
            )
        );
        $signature = base64_encode($hmac);
    }
    return $signature;
}

function fetchApi($api,$data) {

    ksort($data);
    $url = sprintf("GET&%s&%s",urlencode($api),urlencode(http_build_query($data)));


    $data['sig'] = getSignature($url,"dRjTs3P9QLrrruX7&");

    $url = sprintf('https://api.urlshare.cn%s?%s',$api,http_build_query($data));

    $content = file_get_contents($url);

    return json_decode($content,true);
}